package com.thl.intercept;


import com.alibaba.fastjson.JSONObject;
import com.thl.annotation.AuthToken;
import com.thl.utils.ConstantKit;
import com.thl.utils.Md5TokenGenerator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class TockenIntercept implements HandlerInterceptor {

    @Autowired
    Md5TokenGenerator Md5TokenGenerator;

    @Autowired
    StringRedisTemplate redis;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {


        if (!(handler instanceof HandlerMethod)) {//
            System.out.println("handler instanceof HandlerMethod");
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        System.out.println("进入TockenIntercept拦截器:" + method.getName());
        System.out.println(method.getAnnotation(AuthToken.class));
        JSONObject jsonObject = new JSONObject();
        //如果在方法获取类名上打上了@AuthToken则需要进行tocken验证
        if (method.getAnnotation(AuthToken.class) != null || handlerMethod.getBeanType().getAnnotation(AuthToken.class) != null) {
            //获取头部的token
            System.out.println("打上了@AuthToken");
            String token = request.getHeader("tocken");
            PrintWriter out = null;
            System.out.println(token);
            if (token == null || token.equals("")) {

                System.out.println("header token is null");
                try {
                    response.setStatus(401);
                    response.setContentType(MediaType.APPLICATION_JSON_VALUE);
                    jsonObject.put("code", ((HttpServletResponse) response).getStatus());
                    jsonObject.put("hint", ("请求头不包含token"));
                    jsonObject.put("message", HttpStatus.UNAUTHORIZED);
                    out = response.getWriter();
                    out.println(jsonObject);

                    return false;
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (null != out) {
                        out.flush();
                        out.close();
                    }
                }
                return false;

            } else {
                System.out.println(token);
                String redisTokenValue = redis.opsForValue().get(token);
                System.out.println("redisTokenValue：" + redisTokenValue);

                if (redisTokenValue == null || redisTokenValue.equals("")) {
                    try {
                        response.setStatus(401);
                        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
                        jsonObject.put("code", ((HttpServletResponse) response).getStatus());
                        jsonObject.put("hint", ("redis中没有该tocken请登录"));
                        jsonObject.put("message", HttpStatus.UNAUTHORIZED);
                        out = response.getWriter();
                        out.println(jsonObject);
                        return false;
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        if (null != out) {
                            out.flush();
                            out.close();
                        }
                    }
                }

                if (redisTokenValue != null && !redisTokenValue.equals("")) {
                    //验证通过重新设置token过期时间
                    redis.expire(token, ConstantKit.TOKEN_LOGIN_TIME, TimeUnit.SECONDS);

                    System.out.println("redis有效时间："+redis.getExpire(token)+"S");
                    return true;
                }
            }


        } else {
            return true;
        }

        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
